/* eslint-disable @typescript-eslint/no-explicit-any */
import {
    RouteRecordNormalized,
    RouteRecordRaw,
    createRouter,
    createWebHashHistory,
} from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { useSettingStore } from '@/store/setting';
import { useAuthStore } from '@/store/auth';
import { isPathMatch } from '@/utils/validate';
import { getToken } from '@/utils/auth';

// eager：true,默认懒加载
const modules: Record<string, any> = import.meta.glob('./modules/*.ts', {
    eager: true,
});
export const routes: Array<RouteRecordRaw> = [];

Object.keys(modules).forEach((key) => {
    const module = modules[key].default;
    routes.push(module);
});

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});
const handleUpdateBreadcrumb = (currentName: string, currentTitle: string) => {
    const breadcrumbs: string[] = [];
    const routes: RouteRecordNormalized[] = router.getRoutes();
    while (true) {
        if (currentTitle) {
            breadcrumbs.unshift(currentTitle);
        }
        const current = routes.find((item) => item.name === currentName);
        const parentRoute = routes.find(
            (item) => item.name === current?.meta.parentRoute,
        );
        if (parentRoute) {
            currentName = parentRoute.name as string;
            currentTitle = parentRoute.meta.title as string;
            continue;
        } else {
            break;
        }
    }
    useSettingStore().updateBreadcrumbs(breadcrumbs);
};
const whiteList = ['/login', '/register', '/about'];
const isWhiteList = (path: string) => {
    return whiteList.some((pattern) => isPathMatch(pattern, path));
};
router.beforeEach(async (to, _from, next) => {
    NProgress.start();
    const token = getToken();
    console.log('🚀 ~ router.beforeEach ~ token:', token);
    if (getToken()) {
        handleUpdateBreadcrumb(to.name as string, to.meta.title as string);
        const authStore = useAuthStore();
        authStore.setRouteName(to.name as string);
        if (!authStore.authMenuList.length) {
            authStore.getAuthMenuList();
        }
        if (to.path === '/login') {
            next({ path: '/' });
            NProgress.done();
        } else {
            next();
        }
    } else {
        // 没有token
        if (isWhiteList(to.path)) {
            next();
        } else {
            const redirect = encodeURIComponent(to.fullPath || '/');
            next(`/login?redirect=${redirect}`); // 否则全部重定向到登录页
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});

export default router;
